// 配置代理 - 用于联调
const { createProxyMiddleware } = require('http-proxy-middleware')
const bodyParser = require('body-parser')
let { list } = require('./mock')
const Mock = require('mockjs')

module.exports = function (app) {
  app.use(
    createProxyMiddleware('/api', {
      target: 'http://localhost:7001',
      changeOrigin: true,
      pathRewrite: {
        '/api': ''
      }
    })
  )


  app.use(bodyParser.json())

  // 列表请求
  app.get('/lists', (req, res) => {
    const { keyword, type } = req.query;
    let newList = [...list]
    if (keyword) {
      newList = newList.filter(v => {
        return v.id.includes(keyword) || v.type.includes(keyword) || v.nickname.includes(keyword) || v.tel.includes(keyword) || v.address.includes(keyword)
      })
    }
    if (type && type !== '全部') {
      newList = newList.filter(v => {
        return v.type === type
      })
    }
    res.send({
      code: 200,
      data: newList,
      message: '数据获取成功！'
    })
  })
  // 列表删除
  app.delete('/list', (req, res) => {
    // 1. 获取删除的id
    const { id } = req.query;
    // 2. 过滤
    list = list.filter(v => !id.split(',').includes(v.id))
    // 3. 返回
    res.send({
      code: 200,
      message: '数据删除成功！！'
    })
  })
  // 列表更新
  app.post('/list/:id', (req, res) => {
    const { id } = req.body;

    const item = list.find(v => v.id === id)

    // 对象合并
    Object.assign(item, req.body);

    res.send({
      code: 200,
      message: '修改成功'
    })
  })
  // 列表删除
  app.put('/list', (req, res) => {
    req.body.id = Mock.Random.id()
    list.unshift(req.body);
    res.send({
      code: 200,
      message: '添加成功！！！'
    })
  })
  // 列表接口
  app.get('/list/echarts', (req, res) => {
    const map = list.reduce((p, n) => {
      if (p[n.type]) {
        p[n.type]++
      } else {
        p[n.type] = 1
      }
      return p
    }, {})

    res.send({
      code: 200,
      data: map,
      message: '数据获取成功'
    })
  })
}
